package com.example.day11.homework;

import com.example.day05.Circle;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 编写10个线程,t1-计算[1,10]之和,t2->[11,20],....   t10->[91,100],
 * 最后把10个线程的计算结果相加 - result
 */
public class CallableNumDemo implements Callable<Integer> {

    private  int begin;
    private  int end;

    public CallableNumDemo(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {

        int sum=0;
        for (int i=begin;i<=end;i++){
            sum+=i;
        }

        return  sum;
    }
}

class  TestDemo{
    public static void main(String[] args) {
        //创建一个futuretask数组
        FutureTask<Integer> []  futureTasks=new FutureTask[10];

        //创建十个线程
        for(int i=1;i<=10;i++){
            Callable c=new CallableNumDemo((i-1)*10+1,i*10);
            futureTasks[i-1]=new FutureTask<>(c);
            Thread t=new Thread(futureTasks[i-1]);
            t.start();
        }

        Integer result=0;
        for (FutureTask<Integer> futureTask : futureTasks) {

            try {
                result+=futureTask.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.println(result);
    }
}
